﻿//AttributeUsage 特性，跟java中的注解类似，添加注解，通过反射获取


/*[AttributeUsage(
   validon,
   AllowMultiple = allowmultiple,
   Inherited = inherited
)]

参数 validon 规定特性可被放置的语言元素。它是枚举器 AttributeTargets 的值的组合。默认值是 AttributeTargets.All。
参数 allowmultiple（可选的）为该特性的 AllowMultiple 属性（property）提供一个布尔值。如果为 true，则该特性是多用的。默认值是 false（单用的）,true就是一个类上或者方法上可以加多个 Attribute ,false 则不行。
参数 inherited（可选的）为该特性的 Inherited 属性（property）提供一个布尔值。如果为 true，则该特性可被派生类继承。默认值是 false（不被继承）。*/
namespace AuthorAttributeUsage {
    // Multiuse attribute.  
    [System.AttributeUsage(System.AttributeTargets.Class |
                           System.AttributeTargets.Struct,
                           AllowMultiple = true)  // Multiuse attribute.  
    ]
    public class AuthorAttributeUsage : System.Attribute {
        string name;
        public double version;

        public AuthorAttributeUsage(string name) {
            this.name = name;

            // Default value.  
            version = 1.0;
        }

        public string GetName() {
            return name;
        }
    }

    // Class with the Author attribute.  
    [AuthorAttributeUsage("P. Ackerman")]
    public class FirstClass {
        // ...  
    }

    // Class without the Author attribute.  
    public class SecondClass {
        // ...  
    }

    // Class with multiple Author attributes.  
    [AuthorAttributeUsage("P. Ackerman"), AuthorAttributeUsage("R. Koch", version = 2.0)]
    public class ThirdClass {
        // ...  
    }

   public class TestAuthorAttribute {
      public  static void Test() {
            PrintAuthorInfo(typeof(FirstClass));
            PrintAuthorInfo(typeof(SecondClass));
            PrintAuthorInfo(typeof(ThirdClass));
        }

        private static void PrintAuthorInfo(System.Type t) {
            System.Console.WriteLine("Author information for {0}", t);

            // Using reflection.  
            System.Attribute[] attrs = System.Attribute.GetCustomAttributes(t);  // Reflection.  

            // Displaying output.  
            foreach (System.Attribute attr in attrs) {
                if (attr is AuthorAttributeUsage) {
                    AuthorAttributeUsage a = (AuthorAttributeUsage)attr;
                    System.Console.WriteLine("   {0}, version {1:f}", a.GetName(), a.version);
                }
            }
        }
    }

    class TestMain {
        public static void Main(string[] args) {
            TestAuthorAttribute.Test();

                /* 输出:  
        Author information for FirstClass  
           P. Ackerman, version 1.00  
        Author information for SecondClass  
        Author information for ThirdClass  
           R. Koch, version 2.00  
           P. Ackerman, version 1.00  
             */
        }
    }
}
